package com.internal.scan;


import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.Callable;

import org.apache.log4j.Logger;

import com.internal.dispatcher.thread.SpiderRunnable;
import com.internal.fileDataModel.TreeDirectory;



public class ScanFileSystem  implements  Callable<Object>{

	final static Logger log = Logger.getLogger(ScanFileSystem.class);
	private String path;
	private TreeDirectory tree;
	
	public ScanFileSystem (){
		tree = new TreeDirectory();
	}
	
	public ScanFileSystem (String path){
		tree = new TreeDirectory();
		this.path = path;
	}
	
	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	
	
	private void scanning(Path path, int l) throws IOException{
		DirectoryStream<Path> ds = Files.newDirectoryStream(path);
		for (Path p : ds) {
			if(p.toFile().isDirectory())
			{
//				log.info(p.getParent().hashCode());
				tree.insert(p);
				int compare = FileSystems.getDefault().getPath(this.path).compareTo(path);
//				if(compare == l)
//					log.info("root "+p);
//				if(l != 0)
//					log.info("subDirectory - "+p);
////				log.info(compare +" "+l);
//				log.info("Directory - "+p);
				scanning(p,compare);
			}
		}
	}

	

	@Override
	public TreeDirectory call() throws Exception {
		log.info("Scanning to : "+path);
		try {
			Path p = FileSystems.getDefault().getPath(path);
			tree.insert(p);
			this.scanning(p,0);
			
			
		} catch (IOException e) {
			
			log.error(e);
		}
		
		return tree;
	}
}
